package com.bc.web.controller.merch;

import java.util.HashSet;
import java.util.Set;

import com.bc.web.interceptors.AuthInterceptor;
import com.bc.web.model.MerchRole;
import com.bc.web.model.MerchUser;
import com.fs.common.auth.FSAuth;
import com.fs.common.extend.FSController;
import com.fs.common.util.FSMD5;
import com.jfinal.aop.Clear;

@Clear
public class MainController extends FSController {

	public void loginpage() {
		render("login.html");
	}
	
	public void appdown() {
		render("appdown.html");
	}

	public void login() {
		if (!validateCaptcha("captchaCode")) {
			renderFail("验证码错误.");
		} else {
			String userName = getPara("userName");
			String password = FSMD5.codeFor(getPara("password"));
			MerchUser loginUser = MerchUser.dao.loginFind(userName, password);
			if (loginUser != null) {
				if (loginUser.getEnable() == false) {
					renderFail("用户被禁用");
				} else {
					MerchRole role = MerchRole.dao.findById(loginUser.getRoleId());
					if (role == null) {
						renderFail("无角色用户,无法登录");
					} else {

						getSession().setAttribute("merchUser", loginUser);
						getSession().setAttribute("sidebar", AuthInterceptor.getSidebar_merch_zh_CN());
						setAuthAttr(role);
						renderSuccess();
					}
				}
			} else {
				renderFail("用户名/密码错误");
			}
		}
	}

	/**
	 * 将拥有的权限设置到session供标签使用
	 * 
	 * @param role
	 */
	private void setAuthAttr(MerchRole role) {
		// 菜单明细url
		String[] split = role.getSourceUrl().split(",");
		Set<String> menuUrl = new HashSet<>();
		for (String temp : split) {
			menuUrl.add(temp);
		}
		getSession().setAttribute("MERCH" + FSAuth.MENU_URL, menuUrl);

		// 菜单组
		split = role.getSourceGroup().split(",");
		Set<String> menuGroup = new HashSet<>();
		for (String temp : split) {
			menuGroup.add(temp);
		}
		getSession().setAttribute("MERCH" + FSAuth.MENU_GROUP, menuGroup);

	}

	/**
	 * 获取验证码
	 */
	public void getCaptchaCode() {
		renderCaptcha();
	}

	public void logout() {
		getSession().removeAttribute("merchUser");
		redirect("/merch/loginpage");
	}

}
